'use client';

import { useContext, useEffect, useRef, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import type {
  IConfigEmail,
  IConfigImage,
  IConfigJwt,
  IConfigOauthClient,
  IConfigPhone,
  IConfigPost,
  IConfigQq,
  IConfigSection,
  IConfigSite,
  IConfigUser,
} from '@/interfaces';
import {
  queryEmailConfig,
  queryImageConfig,
  queryJwtConfig,
  queryOauthClientConfig,
  queryPhoneConfig,
  queryPostConfig,
  queryQqConfig,
  querySectionConfig,
  querySiteConfig,
  queryUserConfig,
} from '@/services/api';
import Alert from '@/app/[locale]/alert/alert';
import { ConfigAdminContext } from '@/contexts/admin/config';
import AlertLoad from '@/app/[locale]/alert/load';
import UpdateConfigUser from '@/app/[locale]/admin/config/update/user';
import UpdateConfigSection from '@/app/[locale]/admin/config/update/section';
import UpdateConfigPost from '@/app/[locale]/admin/config/update/post';
import UpdateConfigSite from '@/app/[locale]/admin/config/update/site';
import UpdateConfigJwt from '@/app/[locale]/admin/config/update/jwt';
import UpdateConfigQq from '@/app/[locale]/admin/config/update/qq';
import UpdateConfigEmail from '@/app/[locale]/admin/config/update/email';
import UpdateConfigPhone from '@/app/[locale]/admin/config/update/phone';
import UpdateConfigImage from '@/app/[locale]/admin/config/update/image';
import UpdateConfigOauthClient from '@/app/[locale]/admin/config/update/oauthClient';

export default function UpdateConfigAdminPage(this: any) {
  const context = useContext(ConfigAdminContext);
  const updateModalRef = useRef<HTMLDivElement>(null);
  const [type, setType] = useState<Record<string, boolean>>({
    user: false,
    site: false,
    jwt: false,
    section: false,
    post: false,
    qq: false,
    image: false,
    phone: false,
    email: false,
    client: false,
  });

  const queryConfigDetailsQuery = useQuery(
    ['/configs', `/${getTypeId()}`],
    async (context) => {
      const id = context.queryKey[1].substring(1);
      if (id === 'user') {
        return (await queryUserConfig()) as IConfigUser;
      } else if (id === 'section') {
        return (await querySectionConfig()) as IConfigSection;
      } else if (id === 'post') {
        return (await queryPostConfig()) as IConfigPost;
      } else if (id === 'site') {
        return (await querySiteConfig()) as IConfigSite;
      } else if (id === 'jwt') {
        return (await queryJwtConfig()) as IConfigJwt;
      } else if (id === 'qq') {
        return (await queryQqConfig()) as IConfigQq;
      } else if (id === 'email') {
        return (await queryEmailConfig()) as IConfigEmail;
      } else if (id === 'phone') {
        return (await queryPhoneConfig()) as IConfigPhone;
      } else if (id === 'image') {
        return (await queryImageConfig()) as IConfigImage;
      } else if (id === 'client') {
        return (await queryOauthClientConfig()) as IConfigOauthClient;
      }
    },
  );

  useEffect(() => {
    onClickOpenModal();
  }, []);

  function getTypeId() {
    let id = context.updateItem?.id;
    let flag = false;
    for (let typeKey in type) {
      const typeElement = type[typeKey];
      if (typeElement) {
        id = typeKey;
        flag = true;
      }
    }

    if (!flag && id) {
      setType({ ...type, [id]: true });
    }

    return id;
  }

  function onClickMenu(
    item:
      | 'user'
      | 'site'
      | 'jwt'
      | 'section'
      | 'post'
      | 'qq'
      | 'image'
      | 'phone'
      | 'email'
      | 'client',
  ) {
    const newType = {
      user: false,
      site: false,
      jwt: false,
      section: false,
      post: false,
      qq: false,
      image: false,
      phone: false,
      email: false,
      client: false,
    };

    newType[item] = true;
    setType(newType);
  }

  function onClickOpenModal() {
    getUpdateModal().show();
  }

  function onClickCloseModal() {
    if (typeof context.setUpdateItem === 'function') {
      context.setUpdateItem(undefined);
    }
    getUpdateModal().hide();
  }

  function getUpdateModal() {
    const current = updateModalRef.current;
    if (!current) {
      throw '更新元素不存在';
    }

    return window.bootstrap.Modal.getOrCreateInstance(current);
  }

  return (
    <div ref={updateModalRef} className="modal fade" data-bs-backdrop="static">
      <div className="modal-dialog modal-xl modal-dialog-scrollable">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">更新配置</h5>
            <button
              onClick={onClickCloseModal}
              type="button"
              className="btn-close"
              aria-label="Close"
            ></button>
          </div>
          <div className="modal-body">
            {queryConfigDetailsQuery.data && (
              <div className="row">
                <div className="col-auto">
                  <div className="list-group list-group-flush">
                    <button
                      onClick={onClickMenu.bind(this, 'user')}
                      type="button"
                      className="list-group-item list-group-item-action"
                      aria-current="true"
                    >
                      用户
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'site')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      站点
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'jwt')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      令牌
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'section')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      版块
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'post')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      帖子
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'qq')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      QQ
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'image')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      图片
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'phone')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      手机
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'email')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      邮箱
                    </button>
                    <button
                      onClick={onClickMenu.bind(this, 'client')}
                      type="button"
                      className="list-group-item list-group-item-action"
                    >
                      客户端
                    </button>
                  </div>
                </div>
                <div className="col">
                  {type.user && (
                    <UpdateConfigUser
                      details={queryConfigDetailsQuery.data as IConfigUser}
                    />
                  )}

                  {type.section && (
                    <UpdateConfigSection
                      details={queryConfigDetailsQuery.data as IConfigSection}
                    />
                  )}

                  {type.post && (
                    <UpdateConfigPost
                      details={queryConfigDetailsQuery.data as IConfigPost}
                    />
                  )}

                  {type.site && (
                    <UpdateConfigSite
                      details={queryConfigDetailsQuery.data as IConfigSite}
                    />
                  )}

                  {type.jwt && (
                    <UpdateConfigJwt
                      details={queryConfigDetailsQuery.data as IConfigJwt}
                    />
                  )}

                  {type.qq && (
                    <UpdateConfigQq
                      details={queryConfigDetailsQuery.data as IConfigQq}
                    />
                  )}

                  {type.email && (
                    <UpdateConfigEmail
                      details={queryConfigDetailsQuery.data as IConfigEmail}
                    />
                  )}

                  {type.phone && (
                    <UpdateConfigPhone
                      details={queryConfigDetailsQuery.data as IConfigPhone}
                    />
                  )}

                  {type.image && (
                    <UpdateConfigImage
                      details={queryConfigDetailsQuery.data as IConfigImage}
                    />
                  )}

                  {type.client && (
                    <UpdateConfigOauthClient
                      details={
                        queryConfigDetailsQuery.data as IConfigOauthClient
                      }
                    />
                  )}
                </div>
              </div>
            )}

            {queryConfigDetailsQuery.isError && (
              <Alert message={queryConfigDetailsQuery.error} type="error" />
            )}

            {queryConfigDetailsQuery.isLoading && <AlertLoad />}
          </div>
        </div>
      </div>
    </div>
  );
}
